package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.minio.*;
import io.prometheus.client.CollectorRegistry;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;

import java.util.*;
;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
//    private RedissonConfig redissonConfig;
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitService rabbitService;

    //  获取文件上传对应的地址
    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;


    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
        return baseCategory2List;
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
        return baseCategory3List;
    }

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2Id, category3Id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断id是否存在
        if (baseAttrInfo.getId() == null) {
            //if不存在就新增
            baseAttrInfoMapper.insert(baseAttrInfo);
        } else {
            //否则就修改
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }

        //先删除后新增 ,节省性能
        QueryWrapper<BaseAttrValue> qw = new QueryWrapper<>();
        qw.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(qw);
        //获取平台属性值
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //校验非空
        if (!CollectionUtils.isEmpty(attrValueList)) {
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    @Override
    public BaseAttrInfo getAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
//        查询到最新的数据放到集合
        baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        return baseAttrInfo;
    }


    @Override
    public IPage spuInfoIPage(Page<SpuInfo> page1, SpuInfo spuInfo) {
        return spuInfoMapper.selectPage(page1, new QueryWrapper<SpuInfo>().eq("category3_id", spuInfo.getCategory3Id()).orderByDesc("id"));
    }


    @Override
    public String fileUpload(MultipartFile file) {
        // Create a minioClient with the MinIO server playground, its access key and secret key.
        String url = "";
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();

            // Make 'bucketName' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket 'bucketName' already exists.");
            }

            // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
            // 'asiatrip'.
            // 使用putObject上传一个文件到存储桶中
//            minioClient.uploadObject(
//                    UploadObjectArgs.builder()
//                            .bucket(bucketName)
//                            .object(file.getContentType())
//                            .filename("/home/user/Photos/asiaphotos.zip")
//                            .build());
            //  定义一个文件的名称 : 文件上传的时候，名称不能重复！
            String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                    file.getInputStream(), file.getSize(), -1
            ).contentType(file.getContentType()).build());
            url = endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {

        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        /**
         * 对应的表
         *  spuInfo;
         *  spuImage;
         *  spuSaleAttr;
         *  spuSaleAttrValue;
         *  spuPoster
         */
        //保存商品信息
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //判断非空
        if (!CollectionUtils.isEmpty(spuImageList)) {
            //保存spu图片数据
            spuImageList.forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });

        }
        // spuPoster
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)) {
            spuPosterList.forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }
        //spuSaleAttr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });
        }

    }

    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);
        return spuImageMapper.selectList(queryWrapper);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrList(spuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        //sku_info 保存 库存单元表
        skuInfoMapper.insert(skuInfo);
        //sku_image 库存单元图片表
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        skuImageList.forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //sku_attr_value 销售属性值表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        skuAttrValueList.forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //sku_sale_attr_value 与平台属性值的中间表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    @Override
    public IPage list(Page<SkuInfo> skuInfoPage) {
        return skuInfoMapper.selectPage(skuInfoPage, new QueryWrapper<SkuInfo>().orderByDesc("id"));
    }

    @Override
    public void onSale(Long skuId) {
        // 更改销售状态
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);

        //商品上架
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    public void cancelSale(Long skuId) {
        // 更改销售状态
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);

        //商品下架 ‘发送消息
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);

    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {

        String lockKey=skuId+":lock";
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();//上锁

        try {
            QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
            skuInfoQueryWrapper.select("price").eq("id", skuId);
            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
            if (skuInfo != null) {
                return skuInfo.getPrice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
        //默认返回0
        return new BigDecimal("0");
    }

    /**
     * 先查询缓存
     * 缓存中如果没有就查询数据库
     * 把数据库的信息写入缓存
     * 加锁setnx,在查询数据库
     * 如果数据库也没有
     * 保存一个null,缓解一会压力,让请求打到null
     * 释放锁lua
     * 如果没有锁,就休眠一会重试获取锁
     *
     *
     * @param skuId
     * @return
     */
    /**
     * 快速提取ctrl + alt  +m
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = RedisConst.SKUKEY_PREFIX)
    public SkuInfo getSkuInfo(Long skuId) {
//        return  getSkuInfoByRedis(skuId);
//        return getSkuInfoRedisson(skuId);
        return getSkuInfoDB(skuId);
    }

    /**
     * 使用redisson加锁
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoRedisson(Long skuId) {
        //缓存改造
//        return getSkuInfoByRedis(skuId);
        // skuKey sku:24::info
        String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            if (skuInfo==null){
                //上锁
                // set key value ex/px  timeout nx/xx  nx不存在时  xx存在
                String skulock =RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //防止误删uuid
                //加redisson锁
                RLock lock = redissonClient.getLock(skulock);
                //第一个参数是 重试时间  每个请求时间
                boolean result=lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1,RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
//                有锁
                if (result) {
                    try {
                        //业务
                        skuInfo=getSkuInfoDB(skuId);
                        if (skuInfo==null){
                            //保底设置空值null,缓解直接请求到数据库的压力
                            SkuInfo skuInfo1 = new SkuInfo();
                            System.out.println("================null:兜底==================");
                            redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        //如果缓存中没有就从数据库查询,保存到缓存  设置时间
                        redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo;
                    } finally {
                        //解锁
                        lock.unlock();
                    }
                }else {
                    //自旋
                    Thread.sleep(new Random().nextInt(5)*1000);
                    return  getSkuInfo(skuId);
                }
            }else {
                //缓存有数据
                System.out.println("缓存中获取的=================");
                return skuInfo;
            }
        } catch (InterruptedException e) {
            //记录日志,发短信
            e.printStackTrace();
        }
//         直接返回
        return getSkuInfoDB(skuId);
    }

    /**
     * 使用redis+lua  做分布式锁
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoByRedis(Long skuId) {
        //缓存中获取数据
        // skuKey sku:24::info
        String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            if (skuInfo==null){
                //上锁
                // set key value ex/px  timeout nx/xx  nx不存在时  xx存在
                String skulock =RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //防止误删uuid
                String uuid = UUID.randomUUID().toString();
                Boolean result = redisTemplate.opsForValue().setIfAbsent(skulock, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //有锁
                if (result){
                    skuInfo=getSkuInfoDB(skuId);
                    if (skuInfo==null){
                        //保底设置空值null,缓解直接请求到数据库的压力
                        SkuInfo skuInfo1 = new SkuInfo();
                        System.out.println("================null:兜底==================");
                        redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo1;
                    }
                    //如果缓存中没有就从数据库查询,保存到缓存  设置时间
                    redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                    //释放资源redis+lua
                    //  定义一个lua 脚本 if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end;
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

                    //  准备执行lua 脚本
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    //  将lua脚本放入DefaultRedisScript 对象中
                    redisScript.setScriptText(script);
                    //  设置DefaultRedisScript 这个对象的泛型
                    redisScript.setResultType(Long.class);
                    //  执行删除
                    redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
                    return skuInfo;
                }else {
                    //没有锁

                    Thread.sleep(new Random().nextInt(5)*1000);
                    //重试  自旋
                   return getSkuInfo(skuId);
                }
            }else {
                //缓存有数据
                System.out.println("缓存中获取的=================");
                return skuInfo;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//         直接返回
        return getSkuInfoDB(skuId);
    }

    //数据库查询skuinfo
    private SkuInfo getSkuInfoDB(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (skuInfo != null) {
            QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sku_id", skuId);
            List<SkuImage> skuImageList = skuImageMapper.selectList(queryWrapper);
            skuInfo.setSkuImageList(skuImageList);
            return skuInfo;
        }
        return null;
    }

    @Override
    @GmallCache(prefix = "CategoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    @GmallCache(prefix = "SpuSaleAttrListCheckBySku:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    @Override
    @GmallCache(prefix = "SkuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        HashMap<Object, Object> map = new HashMap<>();
        // key = 125|123 ,value = 37
        // 因为是多条所有是list
        List<Map> mapList = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        if (!CollectionUtils.isEmpty(mapList)){
            mapList.forEach(skuMap->{
                map.put(skuMap.get("value_ids"),skuMap.get("sku_id"));
            });
        }
        return map;
    }

    @Override
    @GmallCache(prefix = "SpuPosterBySpuId:")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        QueryWrapper<SpuPoster> spuPosterQueryWrapper = new QueryWrapper<>();
        spuPosterQueryWrapper.eq("spu_id",spuId);
        return spuPosterMapper.selectList(spuPosterQueryWrapper);
    }

    @Override
    @GmallCache(prefix = "AttrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectAttrList(skuId);
    }

    @Override
    @GmallCache(prefix = "BaseCategoryList:")
    public List<JSONObject> getBaseCategoryList() {
        //最外层集合
        // 声明几个json 集合
        ArrayList<JSONObject> list = new ArrayList<>();
        // 声明获取所有分类数据集合
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        // 循环上面的集合并安一级分类Id 进行分组
        Map<Long, List<BaseCategoryView>> category1Map  = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        int index = 1;
        // 获取一级分类下所有数据
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category1Map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator.next();
            // 获取一级分类Id
            Long category1Id  = entry1.getKey();
            // 获取一级分类下面的所有集合
            List<BaseCategoryView> category2List1  = entry1.getValue();
            //
            JSONObject category1 = new JSONObject();
            category1.put("index", index);
            category1.put("categoryId",category1Id);
            // 一级分类名称
            category1.put("categoryName",category2List1.get(0).getCategory1Name());
            // 变量迭代
            index++;
            // 循环获取二级分类数据
            Map<Long, List<BaseCategoryView>> category2Map  = category2List1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            // 声明二级分类对象集合
            List<JSONObject> category2Child = new ArrayList<>();
            // 循环遍历
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category2Map.entrySet().iterator();
            while (iterator1.hasNext()){
                Map.Entry<Long, List<BaseCategoryView>> entry2 = iterator1.next();
                // 获取二级分类Id
                Long category2Id  = entry2.getKey();
                // 获取二级分类下的所有集合
                List<BaseCategoryView> category3List  = entry2.getValue();
                // 声明二级分类对象
                JSONObject category2 = new JSONObject();

                category2.put("categoryId",category2Id);
                category2.put("categoryName",category3List.get(0).getCategory2Name());
                // 添加到二级分类集合
                category2Child.add(category2);

//                List<JSONObject> category3Child = new ArrayList<>();
                List<JSONObject> category3Child = category3List.stream().map(baseCategoryView -> {
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    return category3;
                }).collect(Collectors.toList());
                // 循环三级分类数据
//                category3List.stream().forEach(category3View -> {
//                    JSONObject category3 = new JSONObject();
//                    category3.put("categoryId",category3View.getCategory3Id());
//                    category3.put("categoryName",category3View.getCategory3Name());
//
//                    category3Child.add(category3);
//                });

                // 将三级数据放入二级里面
                category2.put("categoryChild",category3Child);

            }
            // 将二级数据放入一级里面
            category1.put("categoryChild",category2Child);
            list.add(category1);
        }
        return list;
    }

    @Override
    public BaseTrademark getTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }


//    @Transactional(rollbackFor = Exception.class)
//    public void saveSpuInfo(SpuInfo spuInfo) {
//        /**
//         * 对应的表
//         *  spuInfo;
//         *  spuImage;
//         *  spuSaleAttr;
//         *  spuSaleAttrValue;
//         *  spuPoster
//         */
//        //保存商品信息
//        spuInfoMapper.insert(spuInfo);
//        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
//        //判断非空
//        if (!CollectionUtils.isEmpty(spuImageList)){
//            //保存spu图片数据
//            for (SpuImage spuImage : spuImageList) {
//                spuImage.setSpuId(spuInfo.getId());
//                spuImageMapper.insert(spuImage);
//            }
//        }
//        // spuPoster
//        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
//        if (!CollectionUtils.isEmpty(spuPosterList)){
//            for (SpuPoster spuPoster : spuPosterList) {
//                spuPoster.setSpuId(spuInfo.getId());
//                spuPosterMapper.insert(spuPoster);
//            }
//        }
//        //spuSaleAttr
//        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
//        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
//            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
//                spuSaleAttr.setSpuId(spuInfo.getId());
//                spuSaleAttrMapper.insert(spuSaleAttr);
//
//                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
//                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
//                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
//                        spuSaleAttrValue.setSpuId(spuInfo.getId());
//                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
//                    }
//                }
//            }
//        }
//    }


    private List<BaseAttrValue> getAttrValueList(Long attrId) {
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
    }
}
